package gti310.tp4;

public class ZigZag {
	
	/*
	 * L'algo de Zigzag : 
	 * http://stuff.mit.edu/afs/athena/software/gccgo_v4.50/gccgo/libjava/classpath/gnu/javax/imageio/jpeg/ZigZag.java
	 * 
	 * Disponible sur licence GNU.
	 * 
	 * Version adapter a nos besoins.
	 * */
	
	final static boolean ZIGZAG_FORWARD = true;
	final static boolean ZIGZAG_BACKWARD = false;

	static public int[] matrix2List(int[][] matrix, int size) {
		// O(n)
		int[] list = new int[(size * size)];
		boolean direction = ZIGZAG_BACKWARD;
		int x = 0, y = 0, index = 0;
		for (int zigIndex = 0; zigIndex < ((size) * 2 - 1); zigIndex++, direction = !direction) {
			if (direction == ZIGZAG_FORWARD) {
				while (x >= 0 && y != (size)) {
					if (x == (size)) {
						x--;
						y++;
					}
					list[index] = matrix[x][y];
					y++;
					x--;
					index++;
				}
				x++;
			} else {
				while (y >= 0 && x != (size)) {
					if (y == (size)) {
						y--;
						x++;
					}
					list[index] = matrix[x][y];
					y--;
					x++;
					index++;
				}
				y++;
			}
		}
		return list;
	}

	static public double[][] list2Matrix(int[] list, int size) {
		// O(n)
		double[][] matrix = new double[size][size];
		boolean direction = ZIGZAG_FORWARD;
		int x = 0, y = 0, index = 0;
		for (int zigIndex = 0; zigIndex < ((size) * 2 - 1); zigIndex++, direction = !direction) {
			if (direction == ZIGZAG_FORWARD) {
				while (x >= 0 && y != (size)) {
					if (x == (size)) {
						x--;
						y++;
					}
					matrix[x][y] = list[index];
					y++;
					x--;
					index++;
				}
				x++;
			} else {
				while (y >= 0 && x != (size)) {
					if (y == (size)) {
						y--;
						x++;
					}
					matrix[x][y] = list[index];
					y--;
					x++;
					index++;
				}
				y++;
			}
		}
		return matrix;
	}
}
